package com.feng.test.ppt;

import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author HuangSuip
 */
public class PPT2Image {
    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream(new File("E:\\ppt\\化学22.ppt"));
        List<BufferedImage> images = ppt2image(inputStream, true);
    }

    public static List<BufferedImage> ppt2image( InputStream is,boolean isPpt) throws IOException {
        List<BufferedImage> list = new ArrayList<>();
        if (isPpt) {
            HSLFSlideShow slideShow = new HSLFSlideShow(is);
            List<HSLFSlide> slides = slideShow.getSlides();
            for (HSLFSlide slide : slides) {
                Dimension dimension = slide.getSlideShow().getPageSize();
                BufferedImage image = new BufferedImage(
                    (int) dimension.getWidth() + 1, (int) dimension.getHeight() + 1, BufferedImage.TYPE_INT_ARGB);
                Graphics2D graphics2D = image.createGraphics();
                graphics2D.fill(new Rectangle2D.Double(0, 0, dimension.getWidth(), dimension.getHeight()));
                slide.draw(graphics2D);

                try (FileOutputStream fos = new FileOutputStream(
                    new File("E:\\ppt\\slide\\" + UUID.randomUUID() + ".jpg"))) {
/*                int len = 0;
                byte[] b = new byte[1024];
                while ((len = bis.read(b)) != -1) {
                    fos.write(b, 0, len);
                }*/
                    ImageIO.write(image, "png", fos);
                    System.out.println("pic is draw success");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //list.add(image);
            }
        } else {
            XMLSlideShow slideShow = new XMLSlideShow(is);
            List<XSLFSlide> slides = slideShow.getSlides();
            for (XSLFSlide slide : slides) {
                Dimension dimension = slide.getSlideShow().getPageSize();
                BufferedImage image = new BufferedImage(
                    (int) dimension.getWidth() + 1, (int) dimension.getHeight() + 1, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics2D = image.createGraphics();
                graphics2D.fill(new Rectangle2D.Double(0, 0, dimension.getWidth(), dimension.getHeight()));
                slide.draw(graphics2D);
                list.add(image);
            }
        }
        return list;
    }
}
